<script lang="ts" setup>
import { HttpStatusCode } from 'axios'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Delete, Edit } from '@element-plus/icons-vue'
import { delDictItem, manyDelDictItem} from '../../../../api/dict'

const emits = defineEmits(['increase', 'updateData'])
const props = defineProps<{
  dataList: ListDictItem[],
  loading: boolean
}>()
let ids = reactive<string[]>([])

const handleSelectionChange = (val: ListDictItem[]) => {
  ids = val.map(item => {
    return item.id
  })
}
const delMany = () => {
  openDelConfirm(ids)
}
defineExpose({ delMany })
const openDelConfirm = (id: string | string[]) => {
  ElMessageBox.confirm(
      '您确定要删除此记录吗?',
      '删除任务',
      {
        confirmButtonText: '确认删除',
        cancelButtonText: '取消',
        type: 'warning',
      }
  ).then(() => {
    delService(id)
  })
}
const delService = async (id: string | string[]) => {
  let res: Result<string>
  if(typeof id !== 'string') {
    if(id.length === 0) return
    res = await manyDelDictItem(id.join(","))
  } else {
    res = await delDictItem(id)
  }
  if(res.statusCode === HttpStatusCode.Created || res.statusCode === HttpStatusCode.Ok) {
    ElMessage({
      message: res.data as string,
      type: 'success'
    })
    emits('increase', 1, '')
  } else {
    ElMessage({
      message: '删除失败',
      type: 'error'
    })
  }
}
const editService = (form: Meal) => {
  emits('updateData', form)
}
</script>

<template>
  <el-table
      border
      stripe
      v-model:data="props.dataList"
      table-layout="auto"
      v-loading="loading"
      style="width: 100%"
      height="500px"
      @selection-change="handleSelectionChange">
    <el-table-column type="selection" width="30" fixed />
    <el-table-column
        prop="item_label"
        label="属性名"
        align="center"
        fixed="right"
    />
    <el-table-column
        prop="item_value"
        label="属性值"
        align="center"
        fixed="right"
    />
    <el-table-column
        prop="description"
        label="操作"
        align="center"
        fixed="right"
        width="180"
    >
      <template #default="scope">
        <el-button type="warning" size="small" :icon="Edit" circle @click="editService(scope.row)" />
        <el-button type="danger" size="small" :icon="Delete" circle @click="openDelConfirm(scope.row.id)" />
      </template>
    </el-table-column>
  </el-table>
</template>

<style lang="less" scoped>

</style>
